package com.my.test.swing.demo1;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.MenuElement;

/**
 * 
 * @author MAbernethy
 */
public class JMenuButton extends JPanel
{

	private javax.swing.JButton btnMain = null;
	private javax.swing.JButton btnArrow = null;
	private JPopupMenu popup = null;

	private void initialize()
	{
		this.setLayout(new java.awt.BorderLayout());
		this.add(getBtnMain(), java.awt.BorderLayout.CENTER);
		this.add(getBtnArrow(), java.awt.BorderLayout.EAST);
		this.setSize(140, 39);
		getBtnArrow().addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				getPopup().show(getBtnMain(), 0, getHeight());
			}
		}		
		);
	}
	
	public void add(JMenuItem item)
	{
		getPopup().add(item);
	}

	public JMenuButton()
	{
		super();
		initialize();
	}
	
	public void addActionListener(ActionListener l)
	{
		getBtnMain().addActionListener(l);
		for (int i=0; i<getPopup().getSubElements().length; i++)
		{
			JMenuItem e = (JMenuItem)getPopup().getSubElements()[i];
			e.addActionListener(l);
		}		
	}
	
	public void removeActionListener(ActionListener l)
	{
		getBtnMain().removeActionListener(l);
		for (int i=0; i<getPopup().getSubElements().length; i++)
		{
			JMenuItem e = (JMenuItem)getPopup().getSubElements()[i];
			e.removeActionListener(l);
		}		
	}


	private javax.swing.JButton getBtnMain() {
		if(btnMain == null) {
			btnMain = new javax.swing.JButton();
			btnMain.setText("Back");
		}
		return btnMain;
	}
	
	private JPopupMenu getPopup()
	{
		if (popup == null)
		{
			popup = new JPopupMenu();
		}
		return popup;
	}

	private javax.swing.JButton getBtnArrow() {
		if(btnArrow == null) {
			btnArrow = new javax.swing.JButton();
			btnArrow.setPreferredSize(new java.awt.Dimension(16,10));
			btnArrow.setText("V");
			btnArrow.setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 10));
			btnArrow.setMargin(new java.awt.Insets(2,0,2,0));
		}
		return btnArrow;
	}
}  //  @jve:visual-info  decl-index=0 visual-constraint="10,10"
